#!/usr/bin/env python
import pygtk, gtk, gobject
from threading import Thread
from robotparts import link
import copy

"""

TODO LIST: (ordered by pseudo importance)

Implement the menu
Add the possibility to 'update' the name and parent of a link
Add the 'delete' of a link
Add something where you can setup the vis params etc.

"""



class   gui(Thread):

	piter_list = {}

	def run(self):
		gobject.threads_init()
		gtk.main()

	def __init__(self, global_link):
		Thread.__init__(self)        
		builder = gtk.Builder()
		builder.add_from_file('gui/gui.glade')
		builder.connect_signals({'on_button1_clicked':self.klik,'on_treeview1_row_activated':self.treeview_click,'on_update_clicked':self.update_click,'on_delete_clicked':self.delete_click,'on_window1_destroy':gtk.main_quit,'on_help_activate':self.help_btn,'on_open_activate':self.open_file})

		self.window = builder.get_object('window1')
		self.window.set_title("GUI OF AWESOMENESS!")		# TBD !!

		self.gl_link = global_link
		print self.gl_link

		self.treeview = builder.get_object('treeview1')
		self.minlist = builder.get_object('mittree')
		self.column = builder.get_object('minview')
		self.name_ = builder.get_object('name_')
		self.parent = builder.get_object('parent')
		self.dh_d = builder.get_object('dh_d')
		self.dh_a = builder.get_object('dh_a')
		self.dh_alpha = builder.get_object('dh_alpha')
		self.dh_theta = builder.get_object('dh_theta')
		self.name_edit = builder.get_object('name_edit')
		self.parent_edit = builder.get_object('parent_edit')

		self.about_window = builder.get_object('about')
		self.filechooser = builder.get_object('filechooser')
		self.filefilter = builder.get_object('filefilter')

#		self.filefilter

		# create the TreeViewColumn to display the data
		self.tvcolumn = gtk.TreeViewColumn('Links')

		# add tvcolumn to treeview
		self.treeview.append_column(self.tvcolumn)

		# create a CellRendererText to render the data
		self.cell = gtk.CellRendererText()

		# add the cell to the tvcolumn and allow it to expand
		self.tvcolumn.pack_start(self.cell, True)

		# set the cell "text" attribute to column 0 - retrieve text
		# from that column in treestore
		self.tvcolumn.add_attribute(self.cell, 'text', 0)
		self.window.show()

	def klik(self, void):
		if self.name_.get_text() in self.piter_list:
			self.error("There is already a link with that name!")
		elif self.name_.get_text() == "":
			self.error("You need to enter a name for the link!")
		else:
			if self.parent.get_text() == "":
				self.piter_list[self.name_.get_text()] = [self.minlist.append(None, [self.name_.get_text()]),None,0,0,0,0,0,0,0,0]
			elif self.parent.get_text() in self.piter_list:
				self.piter_list[self.name_.get_text()] = [self.minlist.append(self.piter_list[self.parent.get_text()][0], [self.name_.get_text()]),self.parent.get_text(),0,0,0,0,0,0,0,0]
			else:
				self.error("Could not find the parrent!")

	def treeview_click(self, treeviewobject, path, pointer):
		# [piter, parent_name, a, alpha, d, theta, size, color1, color2, color3]
		print self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)]
		if self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][1]:
			self.parent_edit.set_text(self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][1])

		self.name_edit.set_text(self.minlist.get_value(self.minlist.get_iter(path),0))
		self.dh_a.set_text(str(self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][2]))
		self.dh_alpha.set_text(str(self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][3]))
		self.dh_d.set_text(str(self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][4]))
		self.dh_theta.set_text(str(self.piter_list[self.minlist.get_value(self.minlist.get_iter(path),0)][5]))

	def delete_click(self, void):
		self.update_pass_list()

	def update_click(self, void):
		# TODO !! Test that the entered values are valid/makes sense
		self.error("NOTE!!: This function does not yet handle change of name and parent and set all vis=3!")
		piter, store = self.treeview.get_selection().get_selected()

		tmp_list = self.piter_list[piter.get_value(store,0)]
		tmp_list[2] = float(self.dh_a.get_text())		#dh a
		tmp_list[3] = float(self.dh_alpha.get_text())		#dh alpha
		tmp_list[4] = float(self.dh_d.get_text())		#dh d
		tmp_list[5] = float(self.dh_theta.get_text())		#dh theta
		tmp_list[6] = 3		#vis size
		tmp_list[7] = 3		#vis color1
		tmp_list[8] = 3		#vis color2
		tmp_list[9] = 3		#vis color3

		self.piter_list[piter.get_value(store,0)] = tmp_list

	def error(self, msg):
		print "ERROR MSG: " + msg

	def update_pass_list(self):

		obj_list = {}
		tmp_list = {}
		tmp_list = copy.copy(self.piter_list)

		while len(tmp_list) > 0:
			for i in tmp_list:
				if tmp_list[i][1] == None:
					#Parent
					obj_list[i] = link([tmp_list[i][2],tmp_list[i][3],tmp_list[i][4],tmp_list[i][5]], i, None)		#ADD VIS PARMS WHEN NEEDED
					del tmp_list[i]
					break

				elif tmp_list[i][1] in obj_list:
					#child - parent is found
					obj_list[i] = link([tmp_list[i][2],tmp_list[i][3],tmp_list[i][4],tmp_list[i][5]], i, obj_list[tmp_list[i][1]])		#ADD VIS PARMS WHEN NEEDED
					del tmp_list[i]
					break

				else:
					self.error("could not find - (It should be noted, that if this error occurs, I have no idea why)")
					print i
		out_list = []
		for k in obj_list:
			out_list.append(obj_list[k])
		print self.gl_link
		self.gl_link[:] = []		#The list gets cleared totally and then filled with out_list. This could become a problem.
		self.gl_link += out_list

	def help_btn(self, void):
		self.about_window.run()
		self.about_window.hide()

	def open_file(self, void):
		self.filefilter.add_pattern('*.xml')
		res = self.filechooser.run()
		self.filechooser.hide()
		if res == 0:
			print self.filechooser.get_filename()

if __name__ == '__main__' :
	app = gui([])
	app.start()

